package cn.itsource.menu.service.impl;

import cn.itsource.menu.domain.Menu;
import cn.itsource.menu.service.IMenuService;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import org.apache.velocity.runtime.directive.Foreach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Autowired
    private IMenuService menuService;

    @Override
    public List<Menu> deptTree() {
        //查询所有数据
        List<Menu> list = menuService.findAll();
        //创建一个map存储数据 速度快
        //避免双重for循环
        Map<Object, Menu> map = new HashMap<>();
        //创建一个list集合返回数据
        ArrayList<Menu> arrayList = new ArrayList<>();
        //将所有数据存储到map中
        for (Menu menu : list) {
            map.put(menu.getId(),menu);
        }
        //根据数据获取parentid的值
        for (Menu menu : list) {
            //顶级父类没有parentid
            if (menu.getParentId() == null){
                arrayList.add(menu);
            }else {
                //子类获取父类id对象
                Menu menu1 = map.get(menu.getParentId());
                if(menu1 != null){
                menu1.getChildren().add(menu);
                }
            }
        }
        return arrayList;
    }
}
